package com.github.xzb617.client.route.zuul.rules.impl;

import com.github.xzb617.client.route.zuul.constant.RouteRule;
import com.github.xzb617.client.route.zuul.props.RouteProperties;
import com.github.xzb617.client.route.zuul.rules.RoutingRule;
import com.github.xzb617.client.route.zuul.rules.ratio.WeightCalculator;
import com.github.xzb617.client.route.zuul.utils.RouteUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class IpRoutingRule implements RoutingRule {

    @Override
    public void matches(HttpServletRequest request, String ipAddr, RouteProperties.RuleProperties config, RoutingRule routingRuleChain) {
        Map<String, Map<String, RouteRule>> rules = config.getRules();
        Map<String, RouteRule> ipRuleMap = rules.get("IP");
        if (ipRuleMap!=null && !ipRuleMap.isEmpty()) {
            RouteRule routeRule = ipRuleMap.get(ipAddr);
            if (routeRule != null) {
                boolean available = WeightCalculator.available(ipAddr, routeRule.getWeight());
                if (available) {
                    // 匹配IP成功，且在权重范围内，打上标签
                    RouteUtil.assignRouteLabel(routeRule, true);
                } else {
                    RouteUtil.assignRouteLabel(routeRule, false);
                }
            }
        }
    }

}
